Skip to content

edit-schema: use backend preview endpoint for diagram instead of clie…#1797

Merged
gugu merged 1 commit into
mainfrom
feature/schema-diagram-backend-preview
May 22, 2026
Merged

edit-schema: use backend preview endpoint for diagram instead of clie…#1797
gugu merged 1 commit into
mainfrom
feature/schema-diagram-backend-preview

Conversation

@gugu
Copy link
Copy Markdown
Contributor

@gugu gugu commented May 22, 2026

…nt-side SQL parsing

Replace the frontend node-sql-parser AST walk that built the AI-change diagram preview with a call to POST /connection/diagram/:id/preview, so the preview matches what will actually be applied and overlays proposed changes on the real schema. Also bumps pnpm audit overrides.

Summary by CodeRabbit

  • Bug Fixes

    • Schema change operations are no longer blocked if diagram preview generation fails.
    • Failed schema changes now display detailed error information during batch approval.
  • Improvements

    • Enhanced diagram preview generation for more reliable schema visualization.
    • Improved error messaging and reporting across the schema editing workflow.
  • Chores

    • Updated transitive dependency versions for compatibility and stability.

Review Change Stack

…nt-side SQL parsing

Replace the frontend node-sql-parser AST walk that built the AI-change diagram preview with a call to POST /connection/diagram/:id/preview, so the preview matches what will actually be applied and overlays proposed changes on the real schema. Also bumps pnpm audit overrides.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 22, 2026

📝 Walkthrough

Walkthrough

The PR migrates diagram preview generation from local component-side Mermaid building to a backend service endpoint. TableSchemaService gains new preview-response interfaces and a previewDiagram method; the editor component's submission, approval, and rejection flows now request and handle previews asynchronously. Minor formatting refactors and transitive dependency overrides are also included.

Changes

Schema Diagram Preview Backend Integration

Layer / File(s) Summary
Service contract and preview interfaces
frontend/src/app/services/table-schema.service.ts
New exported interfaces ConnectionDiagramPreviewStatementResult, ConnectionDiagramPreviewDiff, and ConnectionDiagramPreviewResponse model the backend response; previewDiagram(connectionId, sqlCommands) method POSTs to /connection/diagram/{connectionId}/preview and returns the typed response; environment import is added and generateSchemaChange is reformatted.
Schema change submission with diagram preview
frontend/src/app/components/edit-database-schema/edit-database-schema.component.ts
onSubmit now awaits previewDiagram call with generated changes' forwardSql, populating previewSource on success and swallowing failures; changes are parsed and a summary message with batchId is appended, followed by a conditional diagram message if preview succeeded; empty-result and error cases append appropriate AI messages.
Approval and rejection flows with change status reporting
frontend/src/app/components/edit-database-schema/edit-database-schema.component.ts
onApprove derives failed changes and appends an error message listing each executionError, or on success clears batchId from pending batch, appends success message, and reloads diagram; onReject filters out "Schema Preview" diagram message, clears pending batchId, and appends rejection message.
Component formatting and helper refactors
frontend/src/app/components/edit-database-schema/edit-database-schema.component.ts
Import statements are reorganized; chatMessages filter, onSubmit message update syntax, _loadDiagram diagram message object construction, _changeMeta fallback return, and _extractDefault function-name extraction are refactored for consistency.
Transitive dependency version pinning
package.json
pnpm.overrides section is extended with new range-to-range mappings for fast-uri, langsmith, ip-address, fast-xml-builder, and brace-expansion.

Sequence Diagram

sequenceDiagram
  participant EditComponent as EditDatabaseSchemaComponent
  participant SchemaService as TableSchemaService
  participant Backend as Backend API
  EditComponent->>SchemaService: previewDiagram(connectionId, sqlCommands)
  SchemaService->>Backend: POST /connection/diagram/{connectionId}/preview
  Backend->>Backend: Generate preview from SQL
  Backend->>SchemaService: ConnectionDiagramPreviewResponse
  SchemaService->>EditComponent: Return preview with statement results and diff
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • rocket-admin/rocketadmin#1750: Implements the backend /connection/diagram/:connectionId endpoint and diagram response model that this PR's service layer now consumes.
  • rocket-admin/rocketadmin#1784: Introduced the live Mermaid preview UI in the schema editor that this PR refactors to consume backend-generated previews instead of local component logic.

Suggested reviewers

  • lyubov-voloshko

Poem

🐰 A diagram dances to the backend's tune,
No longer bound by component cocoon,
With interfaces bright and a preview endpoint,
The schema now sparkles—a fresh new joint! ✨

🚥 Pre-merge checks | ✅ 6
✅ Passed checks (6 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: replacing client-side diagram generation with a backend preview endpoint.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Security Check ✅ Passed Safe SQL parsing without execution. XSS prevented via Angular interpolation. Authorization guard validates access. Input validation enforced. Vulnerable dependencies patched via pnpm overrides.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/schema-diagram-backend-preview

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gugu gugu enabled auto-merge (squash) May 22, 2026 12:26
@coderabbitai coderabbitai Bot requested a review from lyubov-voloshko May 22, 2026 12:26
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
frontend/src/app/components/edit-database-schema/edit-database-schema.component.ts (1)

232-246: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

rejectBatch failure leaves UI in inconsistent state.

If rejectBatch throws, the await completes but the subsequent messages.update() still runs, clearing batchId and removing the preview diagram despite the rejection not being persisted on the backend. Consider wrapping in try/catch to preserve state on failure.

Proposed fix
 async onReject() {
   const batch = this.pendingBatch();
   if (!batch?.batchId) return;

-  await this._tableSchema.rejectBatch(batch.batchId);
-  this.messages.update((msgs) =>
-    msgs
-      .filter((m) => !(m.role === 'diagram' && m.text === 'Schema Preview'))
-      .map((m) => (m === batch ? { ...m, batchId: undefined } : m))
-      .concat({
-        role: 'ai',
-        text: 'Changes rejected. Feel free to describe what you need differently.',
-      }),
-  );
+  try {
+    await this._tableSchema.rejectBatch(batch.batchId);
+    this.messages.update((msgs) =>
+      msgs
+        .filter((m) => !(m.role === 'diagram' && m.text === 'Schema Preview'))
+        .map((m) => (m === batch ? { ...m, batchId: undefined } : m))
+        .concat({
+          role: 'ai',
+          text: 'Changes rejected. Feel free to describe what you need differently.',
+        }),
+    );
+  } catch (err: unknown) {
+    const error = err as { error?: { message?: string }; message?: string };
+    this.messages.update((msgs) => [
+      ...msgs,
+      {
+        role: 'error',
+        text: error?.error?.message || error?.message || 'Failed to reject changes.',
+      },
+    ]);
+  }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@frontend/src/app/components/edit-database-schema/edit-database-schema.component.ts`
around lines 232 - 246, The onReject handler currently calls await
this._tableSchema.rejectBatch(batch.batchId) but always runs messages.update
afterwards, which can clear batchId and remove the preview even if the backend
call fails; modify onReject (use pendingBatch() to get the batch) to wrap the
rejectBatch call in a try/catch and only perform messages.update when
rejectBatch succeeds, and in the catch preserve the existing messages state and
surface the error (e.g., log or show a user notification) so the UI remains
consistent if _tableSchema.rejectBatch throws.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In
`@frontend/src/app/components/edit-database-schema/edit-database-schema.component.ts`:
- Around line 232-246: The onReject handler currently calls await
this._tableSchema.rejectBatch(batch.batchId) but always runs messages.update
afterwards, which can clear batchId and remove the preview even if the backend
call fails; modify onReject (use pendingBatch() to get the batch) to wrap the
rejectBatch call in a try/catch and only perform messages.update when
rejectBatch succeeds, and in the catch preserve the existing messages state and
surface the error (e.g., log or show a user notification) so the UI remains
consistent if _tableSchema.rejectBatch throws.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e8432947-6173-4446-b8bf-37618e5334f6

📥 Commits

Reviewing files that changed from the base of the PR and between 08edb38 and 2147b84.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • frontend/src/app/components/edit-database-schema/edit-database-schema.component.ts
  • frontend/src/app/services/table-schema.service.ts
  • package.json

@gugu gugu merged commit f80c6a0 into main May 22, 2026
19 checks passed
@gugu gugu deleted the feature/schema-diagram-backend-preview branch May 22, 2026 12:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant